package com.briup.estore.util;

import com.briup.estore.bean.Customer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 封装一些可能用到的方法
 */
public class CommonUtil {
    public static Integer getUserId(HttpServletRequest request){
        Integer userId = -1;
        HttpSession session = request.getSession();
        // 查询所有地址信息（用户id可以直接从session里取）
        // 先从session里取
        Customer user = (Customer) session.getAttribute("user");
        // 如果session里没有，从cookie里取
        if (user == null){
            Cookie[] cookies = request.getCookies();
            for (Cookie c : cookies) {
                if ("userId".equals(c.getName())){
                    userId = Integer.parseInt(c.getValue());
                }
            }
        }else {
            userId = user.getId();
        }
        return userId;
    }
}
